<template>
  <div class="shipping-management">
    <!-- 筛选栏 -->
    <el-form :inline="true" :model="filters" class="filter-form">
      <el-form-item label="订单状态">
        <el-select v-model="filters.status" placeholder="全部" clearable>
          <el-option label="全部" value="" />
          <el-option label="待发货" value="待发货" />
          <el-option label="待提货" value="待提货" />
          <el-option label="待评价" value="待评价" />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间">
        <el-date-picker
          v-model="filters.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
        <el-button type="success" @click="onBatchShip">批量发货</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计栏 -->
    <div class="stat-bar">
      <el-tag type="info">待发货订单: {{ stat.pendingShipment }}</el-tag>
      <el-tag type="primary">待提货订单: {{ stat.pendingPickup }}</el-tag>
      <el-tag type="success">已完成订单: {{ stat.completed }}</el-tag>
    </div>

    <!-- 表格 -->
    <el-table 
      :data="orderList" 
      border 
      style="width: 100%"
      v-loading="loading"
      @selection-change="onSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="orderId" label="订单号" width="180" />
      <el-table-column prop="shipTime" label="发货时间" width="180">
        <template #default="{ row }">
          {{ getShipTime(row) }}
        </template>
      </el-table-column>
      <el-table-column prop="caption" label="所属团长" width="150" />
      <el-table-column prop="driverName" label="运输司机" width="120">
        <template #default="{ row }">
          {{ getDriverName(row) }}
        </template>
      </el-table-column>
      <el-table-column prop="driverPhone" label="联系方式" width="130">
        <template #default="{ row }">
          {{ getDriverPhone(row) }}
        </template>
      </el-table-column>
      <el-table-column prop="plateNumber" label="车牌号" width="120">
        <template #default="{ row }">
          {{ getPlateNumber(row) }}
        </template>
      </el-table-column>
      <el-table-column prop="pickupCode" label="提货码" width="100">
        <template #default="{ row }">
          <el-tag v-if="getPickupCode(row) !== '-'" type="success">
            {{ getPickupCode(row) }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template #default="{ row }">
          <el-button 
            v-if="row.status === '待发货'" 
            type="success" 
            size="small" 
            @click="onShip(row)"
          >
            发货
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="onPageChange"
        @size-change="onSizeChange"
      />
    </div>

    <!-- 发货弹窗 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="确认发货"
      width="600px"
    >
      <div v-if="currentOrder">
        <el-form :model="shipForm" label-width="100px">
          <el-form-item label="订单号">
            <span>{{ currentOrder.orderId }}</span>
          </el-form-item>
          <el-form-item label="收货地址">
            <span>{{ currentOrder.deliveryAddress }}</span>
          </el-form-item>
          <el-form-item label="所属团长">
            <span>{{ currentOrder.caption }}</span>
          </el-form-item>
          <el-form-item label="运输司机">
            <el-input
              v-model="shipForm.driverName"
              placeholder="请输入运输司机姓名"
            />
          </el-form-item>
          <el-form-item label="司机电话">
            <el-input
              v-model="shipForm.driverPhone"
              placeholder="请输入司机联系电话"
            />
          </el-form-item>
          <el-form-item label="车牌号">
            <el-input
              v-model="shipForm.plateNumber"
              placeholder="请输入车牌号"
            />
          </el-form-item>
          <el-form-item label="发货备注">
            <el-input
              v-model="shipForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入发货备注信息"
            />
          </el-form-item>
          <el-form-item label="物流信息">
            <el-input
              v-model="shipForm.logistics"
              placeholder="请输入物流信息（可选）"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="shipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShip">确认发货</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量发货弹窗 -->
    <el-dialog
      v-model="batchShipDialogVisible"
      title="批量发货"
      width="600px"
    >
      <div>
        <p>确认将选中的 <strong>{{ selectedOrders.length }}</strong> 个订单标记为已发货？</p>
        
        <!-- 批量发货司机信息表单 -->
        <el-form
          ref="batchShipFormRef"
          :model="batchShipForm"
          :rules="batchShipRules"
          label-width="100px"
          style="margin-top: 20px;"
        >
          <el-form-item label="司机姓名" prop="driverName">
            <el-input
              v-model="batchShipForm.driverName"
              placeholder="请输入司机姓名"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="司机电话" prop="driverPhone">
            <el-input
              v-model="batchShipForm.driverPhone"
              placeholder="请输入司机电话"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="车牌号" prop="plateNumber">
            <el-input
              v-model="batchShipForm.plateNumber"
              placeholder="请输入车牌号"
              clearable
            />
          </el-form-item>
          
          <el-form-item label="备注">
            <el-input
              v-model="batchShipForm.remark"
              placeholder="请输入备注信息（可选）"
              type="textarea"
              :rows="2"
            />
          </el-form-item>
          
          <el-form-item label="物流信息">
            <el-input
              v-model="batchShipForm.logistics"
              placeholder="请输入物流信息（可选）"
              type="textarea"
              :rows="2"
            />
          </el-form-item>
        </el-form>
        
        <el-alert
          title="批量发货说明"
          type="info"
          :closable="false"
          style="margin-top: 10px;"
        >
          <template #default>
            <p>• 批量发货会将订单状态从"待发货"更新为"待提货"</p>
            <p>• 发货后用户可以在订单页面查看订单状态和司机信息</p>
            <p>• 建议在发货前确认商品质量和包装完整性</p>
            <p>• 司机信息将记录在订单历史记录中</p>
          </template>
        </el-alert>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchShipDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBatchShip" :loading="loading">确认批量发货</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

// 响应式数据
const loading = ref(false);
const orderList = ref([]);
const historyList = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const shipDialogVisible = ref(false);
const batchShipDialogVisible = ref(false);
const currentOrder = ref(null);
const selectedOrders = ref([]);

// 筛选条件
const filters = reactive({
  status: "",
  dateRange: []
});

// 发货表单
const shipForm = reactive({
  driverName: "",
  driverPhone: "",
  plateNumber: "",
  remark: "",
  logistics: ""
});

// 批量发货表单
const batchShipForm = ref({
  driverName: '',
  driverPhone: '',
  plateNumber: '',
  remark: '',
  logistics: ''
});

// 批量发货表单验证规则
const batchShipRules = ref({
  driverName: [
    { required: true, message: '请输入司机姓名', trigger: 'blur' }
  ],
  driverPhone: [
    { required: true, message: '请输入司机电话', trigger: 'blur' }
  ],
  plateNumber: [
    { required: true, message: '请输入车牌号', trigger: 'blur' }
  ]
});

// 统计数据
const stat = reactive({
  pendingShipment: 0,
  pendingPickup: 0,
  completed: 0
});

// 获取历史记录
const fetchHistory = async () => {
  try {
    // 获取当前订单列表的所有orderId
    const orderIds = orderList.value.map(order => order.orderId);
    if (orderIds.length === 0) {
      historyList.value = [];
      return;
    }
    const response = await axios.post('http://localhost:3000/hy/order-history/batch', {
      orderIds
    });
    if (response.data.code === 200) {
      historyList.value = response.data.data.list;
      console.log('历史记录：', historyList.value);
    } else {
      ElMessage.error(response.data.message || '获取历史记录失败');
    }
  } catch (error) {
    console.error('获取历史记录失败:', error);
    ElMessage.error('获取历史记录失败');
  }
};

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true;
    
    const params = {
      page: currentPage.value,
      limit: pageSize.value,
      status: filters.status,
      startDate: filters.dateRange?.[0],
      endDate: filters.dateRange?.[1]
    };

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key];
      }
    });

    console.log('请求参数：', params);

    const response = await axios.get('http://localhost:3000/hy/orders', { params });
    
    if (response.data.code === 200) {
      orderList.value = response.data.data.list;
      total.value = response.data.data.total;

      console.log('订单列表：', orderList.value);
      
      // 更新统计数据
      updateStats();
    } else {
      ElMessage.error(response.data.message || '获取订单列表失败');
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败');
  } finally {
    loading.value = false;
  }
};

// 更新统计数据
const updateStats = () => {
  stat.pendingShipment = orderList.value.filter(order => order.status === '待发货').length;
  stat.pendingPickup = orderList.value.filter(order => order.status === '待提货').length;
  stat.completed = orderList.value.filter(order => 
    order.status === '待评价' || order.status === '已退款'
  ).length;
};

// 获取发货时间
const getShipTime = (row) => {
  const history = historyList.value.find(h => h.orderId === row.orderId);
  if (history) {
    const shipHistory = history.historyList.find(h => h.type === '发货时间');
    return shipHistory?.time === '-' ? '-' : formatDate(shipHistory?.time);
  }
  return '-';
};

// 获取司机姓名
const getDriverName = (row) => {
  const history = historyList.value.find(h => h.orderId === row.orderId);
  if (history) {
    const shipHistory = history.historyList.find(h => h.type === '发货时间');
    return shipHistory?.driverName === '-' ? '-' : shipHistory?.driverName || '-';
  }
  return '-';
};

// 获取司机电话
const getDriverPhone = (row) => {
  const history = historyList.value.find(h => h.orderId === row.orderId);
  if (history) {
    const shipHistory = history.historyList.find(h => h.type === '发货时间');
    return shipHistory?.driverPhone === '-' ? '-' : shipHistory?.driverPhone || '-';
  }
  return '-';
};

// 获取车牌号
const getPlateNumber = (row) => {
  const history = historyList.value.find(h => h.orderId === row.orderId);
  if (history) {
    const shipHistory = history.historyList.find(h => h.type === '发货时间');
    return shipHistory?.plateNumber === '-' ? '-' : shipHistory?.plateNumber || '-';
  }
  return '-';
};

// 获取提货码
const getPickupCode = (row) => {
  return row.pickupCode || '-';
};

// 更新订单状态
const updateOrderStatus = async (orderId, status, shipData = {}) => {
  try {
    console.log('开始更新订单状态:', orderId, status, shipData);
    
    const response = await axios.put(`http://localhost:3000/hy/orders/${orderId}/status`, { 
      status,
      ...shipData
    });
    
    if (response.data.code === 200) {
      console.log('订单状态更新成功');
      return response; // 返回完整的响应
    } else {
      ElMessage.error(response.data.message || '更新订单状态失败');
      return false;
    }
  } catch (error) {
    console.error('更新订单状态失败:', error);
    ElMessage.error('更新订单状态失败');
    return false;
  }
};

// 事件处理
const onSearch = () => {
  currentPage.value = 1;
  fetchOrders();
};

const onReset = () => {
  Object.assign(filters, {
    status: "",
    dateRange: []
  });
  currentPage.value = 1;
  fetchOrders();
};

const onPageChange = (page) => {
  currentPage.value = page;
  fetchOrders();
};

const onSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchOrders();
};

const onSelectionChange = (selection) => {
  selectedOrders.value = selection;
};

const onShip = (row) => {
  currentOrder.value = row;
  // 重置发货表单
  Object.assign(shipForm, {
    driverName: "",
    driverPhone: "",
    plateNumber: "",
    remark: "",
    logistics: ""
  });
  shipDialogVisible.value = true;
};

const onBatchShip = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning('请先选择要发货的订单');
    return;
  }
  
  const pendingOrders = selectedOrders.value.filter(order => order.status === '待发货');
  if (pendingOrders.length === 0) {
    ElMessage.warning('选中的订单中没有待发货的订单');
    return;
  }
  
  batchShipDialogVisible.value = true;
};

// 确认发货
const confirmShip = async () => {
  if (!currentOrder.value) return;
  
  // 验证必填字段
  if (!shipForm.driverName || !shipForm.driverPhone || !shipForm.plateNumber) {
    ElMessage.warning('请填写运输司机、司机电话和车牌号');
    return;
  }
  
  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(shipForm.driverPhone)) {
    ElMessage.warning('请输入正确的手机号码');
    return;
  }
  
  try {
    loading.value = true;
    
    const shipData = {
      driverName: shipForm.driverName,
      driverPhone: shipForm.driverPhone,
      plateNumber: shipForm.plateNumber,
      remark: shipForm.remark,
      logistics: shipForm.logistics,
      shipTime: new Date().toISOString()
    };
    
    const success = await updateOrderStatus(currentOrder.value.orderId, '待提货', shipData);
    if (success) {
      shipDialogVisible.value = false;
      // 获取生成的提货码
      const pickupCode = success.data?.pickupCode || '未知';
      // 重新获取数据
      await fetchHistory();
      fetchOrders();
    }
  } catch (error) {
    console.error('发货失败:', error);
    ElMessage.error('发货失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 确认批量发货
const confirmBatchShip = async () => {
  const pendingOrders = selectedOrders.value.filter(order => order.status === '待发货');
  
  if (pendingOrders.length === 0) {
    ElMessage.warning('选中的订单中没有待发货的订单');
    return;
  }
  
  // 验证批量发货表单
  if (!batchShipForm.value.driverName || !batchShipForm.value.driverPhone || !batchShipForm.value.plateNumber) {
    ElMessage.warning('请填写完整的司机信息');
    return;
  }
  
  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(batchShipForm.value.driverPhone)) {
    ElMessage.warning('请输入正确的手机号码');
    return;
  }
  
  try {
    loading.value = true;
    let successCount = 0;
    
    for (const order of pendingOrders) {
      const shipData = {
        driverName: batchShipForm.value.driverName,
        driverPhone: batchShipForm.value.driverPhone,
        plateNumber: batchShipForm.value.plateNumber,
        remark: batchShipForm.value.remark || '批量发货',
        logistics: batchShipForm.value.logistics || '',
        shipTime: new Date().toISOString()
      };
      
      const success = await updateOrderStatus(order.orderId, '待提货', shipData);
      if (success) {
        successCount++;
        // 记录提货码信息
        const pickupCode = success.data?.pickupCode;
        if (pickupCode) {
          console.log(`订单 ${order.orderId} 提货码: ${pickupCode}`);
        }
      }
      
      // 添加小延迟避免请求过快
      await new Promise(resolve => setTimeout(resolve, 100));
    }
    
    batchShipDialogVisible.value = false;
    // 清空批量发货表单
    batchShipForm.value = {
      driverName: '',
      driverPhone: '',
      plateNumber: '',
      remark: '',
      logistics: ''
    };
    ElMessage.success(`批量发货完成，成功发货 ${successCount} 个订单`);
    
    // 重新获取数据
    await fetchHistory();
    fetchOrders();
  } catch (error) {
    console.error('批量发货失败:', error);
    ElMessage.error('批量发货失败');
  } finally {
    loading.value = false;
  }
};

// 工具函数
const formatDate = (dateString) => {
  if (!dateString || dateString === '-') return '-';
  return new Date(dateString).toLocaleString('zh-CN');
};

const getStatusType = (status) => {
  const statusMap = {
    '待付款': 'warning',
    '待发货': 'info',
    '待提货': 'primary',
    '待评价': 'success',
    '退款中': 'danger',
    '已退款': 'danger',
    '已取消': 'info'
  };
  return statusMap[status] || 'info';
};

// 初始化
onMounted(async () => {
  await fetchOrders();
  await fetchHistory();
});
</script>

<style scoped>
.shipping-management {
  padding: 20px;
}

.filter-form {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-bar {
  margin-bottom: 20px;
}

.stat-bar .el-tag {
  margin-right: 15px;
  font-size: 14px;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

.dialog-footer {
  text-align: right;
}
</style>
